import { request } from '../../request/index'
//使用async await需要引入，只引入就行
import regeneratorRuntime from '../../lib/runtime/runtime'

// pages/category/category.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    leftList: [],
    rightList: [],
    currentIndex: 0,
    scrollTop: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const categoryData = wx.getStorageSync("categoryData");
    if (!categoryData) {
      this.getCategory()
    } else {
      const time = Date.now() - categoryData.create_time
      const dataArr = categoryData.dataArr
      if (time > 1000 * 60 * 5) {
        this.getCategory()
      } else {
        this.cateData = dataArr
        const leftList = dataArr.map(item => item.cat_name)
        const rightList = dataArr[0].children
        this.setData({
          leftList,
          rightList
        })
      }
    }
  },

  //获取分类页面数据
  async getCategory() {
    const result = await request({url:'/categories'}) 
    this.cateData = result.data.message
    wx.setStorageSync("categoryData", { create_time: Date.now(), dataArr: result.data.message });
    const leftList = this.cateData.map(item => item.cat_name)
    const rightList = this.cateData[0].children
    this.setData({
      leftList,
      rightList
    })   
  },

  //左侧item项点击事件
  leftItemClick(event) {
    const currentIndex = event.currentTarget.dataset.index
    const rightList = this.cateData[currentIndex].children
    this.setData({
      currentIndex,
      rightList,
      scrollTop: 0
    })
  },

  //做本地化存储，避免请求发送过于频繁


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})